package registration;

import static org.junit.Assert.*;

import java.util.*;

import msg.*;

import org.junit.Test;

import common.DBTest;
import common.dal.Transaction;
import common.exceptions.*;
import common.interfaces.IPersistent;

@SuppressWarnings({"javadoc", "static-method"})
public class DBConsensusManagerTest extends DBTest {
	private static DBConsensusManager	$;
	
	@Override
	protected IPersistent setPersistent(Transaction t) {
		$ = new DBConsensusManager(t);
		return $;
	}
	
	@Override
	protected IPersistent getPersistent() {
		return $;
	}
	
	@Test(expected = InvalidEventException.class)
	public void testAddBadEvent() throws Exception {
		Consensus con = new Consensus(0, "test", getFakeEvent());
		$.persist(con);
	}
	
	@Test(expected = ExistingEntityException.class)
	public void testAddRepeatIds() throws Exception {
		Consensus con = new Consensus(0, "test", getEvent());
		$.persist(con);
		// second add fails
		$.persist(con);
	}
	
	@Test
	public void testAdd() throws Exception {
		Consensus con = new Consensus(0, "test", getEvent());
		$.persist(con);
		Consensus result = $.get(0L);
		assertEquals(con, result);
	}
	
	@Test(expected = InvalidEventException.class)
	public void testGetAllConsensusesBadEvent() throws Exception {
		$.getAllEventConsensuses(getFakeEvent());
	}
	
	@Test(expected = InvalidEventException.class)
	public void testGetAllConsensusesMessageId() throws Exception {
		EventMessage event = MessageManager.getNewInstance(t)
				.createNewEventMessage(new Location(0.5, 0.5), "", getUser(), getTomorrow(), 10);
		MessageManager.getNewInstance(t).delete(event.getId());
		$.getAllEventConsensuses(event);
	}
	
	@Test
	public void testGetAllConsensuses() throws Exception {
		Consensus con = new Consensus(0, "test", getEvent());
		$.persist(con);
		Consensus con2 = new Consensus(1, "test2", getEvent());
		EventMessage event = MessageManager.getNewInstance(t)
				.createNewEventMessage(getEvent().getLocation(), "another event", getUser(), getTomorrow(), 5);
		$.persist(con2);
		Set<Consensus> expected = new HashSet<>(Arrays.asList(con, con2));
		con = new Consensus(2, "test3", event);
		$.persist(con);
		assertEquals(expected, new HashSet<>($.getAllEventConsensuses(getEvent())));
	}
	
	@Test
	public void removeAllConsensuses() throws Exception {
		Consensus con = new Consensus(0, "test", getEvent());
		$.persist(con);
		EventMessage event = MessageManager.getNewInstance(t)
				.createNewEventMessage(getEvent().getLocation(), "another event", getUser(), getTomorrow(), 5);
		Consensus con2 = new Consensus(1, "test2", event);
		$.persist(con2);
		$.removeAllConsensuses(getEvent());
		Set<Consensus> expected = new HashSet<>(Arrays.asList(con2));
		assertEquals(expected, new HashSet<>($.getAll()));
	}
}
